Page({
  data: {
    phone: '',
    password: '',
    confirmPassword: '',
    name: '',
    code: '',
    agreementChecked: false
  },
  onLoad: function () {
    // 页面加载时的逻辑
  },
  onPhoneChange(e) {
    this.setData({
      phone: e.detail
    });
  },
  onPasswordChange(e) {
    this.setData({
      password: e.detail
    });
  },
  onConfirmPasswordChange(e) {
    this.setData({
      confirmPassword: e.detail
    });
  },
  onNameChange(e) {
    this.setData({
      name: e.detail
    });
  },
  onCodeChange(e) {
    this.setData({
      code: e.detail
    });
  },
  onAgreementChange(e) {
    this.setData({
      agreementChecked: e.detail.value.includes('agreement')
    });
  },
  getVerificationCode() {
    if (!this.data.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }
    wx.showToast({
      title: '验证码已发送',
      icon: 'none'
    });
    // 这里添加发送验证码的逻辑
    // 实际项目中，你需要调用后端接口发送验证码
  },
  bindPhone() {
    if (!this.data.agreementChecked) {
      wx.showToast({
        title: '请同意注册协议',
        icon: 'none'
      });
      return;
    }
    if (this.data.confirmPassword !== this.data.password) {
      wx.showToast({
        title: '两次输入密码不一致',
        icon: 'none'
      });
      return;
    }

    // 发起注册请求
    wx.request({
      url: 'http://localhost:8080/hqy/users/register', // 替换为你的后端注册接口地址
      method: 'POST',
      data: {
        tel: this.data.phone,
        password: this.data.password,
        username: this.data.name,
        code: this.data.code,
        nickname: this.data.name,
        points: 0
      },
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 注册成功
          wx.showToast({
            title: '注册成功',
            icon: 'success',
            duration: 2000
          });

          // 将token存储到全局变量中
          const app = getApp();
          app.globalData.token = res.data.data.token;

          // 跳转到登录页面或其他页面
          wx.navigateBack(); // 返回上一页
        } else {
          // 注册失败
          wx.showToast({
            title: res.data.message || '注册失败',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 2000
        });
        console.error('注册请求失败:', err);
      }
    });
  },
  navigateBack() {
    wx.navigateBack(); // 返回上一页
  }
});